<?php

namespace app\selladmin\model;

use think\Model;
use think\Db;
use app\selladmin\model\Reply;

/*
 * 订单
 */

class Comment extends Model {

    //评论对应的用户信息
    public function Custom() {
        return $this->hasOne('Custom', 'id', 'ctm_id')->field('id,custom_name,real_name,custom_phone,custom_photo');
    }

    //回复对应的员工信息
    public function Staff() {
        return $this->belongsTo('Staff', 'staff_id', 'id')->field('id,staff_name,staff_photo');
    }

    //评论对应的店铺信息
    public function Store() {
        return $this->hasOne('Store', 'id', 'store_id')->field('id,store_name');
    }

    //评论对应的店铺信息
    public function Reply() {
        return $this->hasOne('Reply', 'comment_id', 'id');
    }

    //查询评价列表
    public function CommentList($order_id, $staff_id, $store_id, $ctm_id, $item_id, $pagenum) {
        if ($order_id) {
            $commentwhere['order_id'] = $order_id;
        }
        if ($staff_id) {
            $commentwhere['staff_id'] = $staff_id;
        }
        if ($store_id) {
            $commentwhere['store_id'] = $store_id;
        }
        if ($ctm_id) {
            $commentwhere['ctm_id'] = $ctm_id;
        }
        if ($item_id) {
            $commentwhere['item_id'] = $item_id;
        }
        $commentwhere = isset($commentwhere) ? $commentwhere : '';
        $commentList = Comment::with('Custom,Staff')
                ->where($commentwhere)
                ->order("add_time desc")
                ->paginate($pagenum)
                ->appends($commentwhere);
        return $commentList;
    }

    //查询评价详情
    public function CommentDetails($id) {
        $commentwhere['id'] = $id;
        $CommentDetails = Comment::with('Custom,Staff')
                ->where($commentwhere)
                ->find();
        $CommentDetails['image']=  json_decode($CommentDetails['image'],true);
        return $CommentDetails;
    }
    
    /*
     * 某个项目平均评价星级
     */
    public static function getItemCommentStar($item_id)
    {
        $star = 5;

        $count = Db::name('comment')->where('item_id', '=', $item_id)->count();

        if ($count > 0) {
            $starSum = Db::name('comment')->where('item_id', '=', $item_id)->sum('star');

            $count = $count + 1;
            $starSum = $starSum + 5;

            $star = round($starSum / $count, 1);
        }

        return $star;
    }
    
    /*
     * 某个项目评论数量
     */
    public static function getItemCommentCount($item_id)
    {
        $count = Db::name('comment')->where('item_id', '=', $item_id)->count();

        return $count;
    }

}
